package com.ezia.coreservices.charging.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/*
 * AES加解密算法 
 * 
 * @author yangcheng
 */
public class AESUtils {
	private final static Logger logger = LoggerFactory.getLogger(AESUtils.class);

	// 加密
	public static String Encrypt(String sSrc, String keyStr, String ivStr) throws Exception {

		if (StringUtils.isBlank(keyStr)) {
			logger.error("没有传入AES加密的加密秘钥");
			return null;
		}

		if (StringUtils.isBlank(ivStr)) {
			logger.error("没有传入AES CBC加密的加密向量");
			return null;
		}

		if (keyStr.length() != 16) {
			logger.error("AES加密的加密秘钥长度不是16位");
			return null;
		}

		SecretKeySpec skeySpec = new SecretKeySpec(keyStr.getBytes(), "AES");

		// "算法/模式/补码方式"
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

		// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
		IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());

		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

		byte[] encrypted = cipher.doFinal(sSrc.getBytes());
		String str = new BASE64Encoder().encode(encrypted);
		return str.replaceAll("\r\n", "");
	}

	// 解密
	public static String Decrypt(String sSrc, String sKey, String ivStr) throws Exception {
		try {
			// 判断Key是否正确
			if (sKey == null) {
				System.out.print("Key为空null");
				return null;
			}
			// 判断Key是否为16位
			if (sKey.length() != 16) {
				System.out.print("Key长度不是16位");
				return null;
			}
			byte[] raw = sKey.getBytes("UTF-8");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
			try {
				byte[] original = cipher.doFinal(encrypted1);
				String originalString = new String(original);
				// originalString= unEscapeChar(originalString);
				return originalString;
			} catch (Exception e) {
				System.out.println(e.toString());
				return null;
			}
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return null;
		}
	}

}
